import Utils from "../utils/Utils";

export default class WebScorket {

    private _ws: Laya.Socket;

    connect(host: string, port: number) {

        let ws = this._ws;
        Utils.isNil(ws) && (ws = this._ws = new Laya.Socket());

        ws.offAllCaller(this);
        ws.on(Laya.Event.OPEN, this, this.onOpen);
        ws.on(Laya.Event.MESSAGE, this, this.onMessage);
        ws.on(Laya.Event.CLOSE, this, this.onClose);
        ws.on(Laya.Event.ERROR, this, this.onError);

        if (ws.connected) {
            console.log("已连接成功");
            return;
        }

        ws.connect(host, port);
    }

    send(param: any) {
        let ws = this._ws;
        let data = param;
        ws.send(data);
    }

    close() {
        let ws = this._ws;
        ws && ws.close();
    }

    private onOpen() {

    }

    private onMessage(data: any) {

    }

    private onClose() {

    }


    private onError(err: any) {

    }


}